<template> 
    <div class="design flex-center ">
        <div class="pdfBtn">
            <div><button class="pointer" style="margin-left:21px" @click="openDefault" v-if="systemFile" :class="[Default ? 'activeBtn':'']">默认教案</button></div>
            <div v-for="(item,index) in syncList" :key="index">
                <button class="syncPdf pointer" @click="changeSyncFile(item,index)" :class="[syncActive === index ? 'activeBtn' : '']" >同步教案{{index+1}}</button>
            </div>
        </div>
        <div class="test" v-if="DefaultPdf && online" ref="test">
            

            <div v-if="eduLevel!=='primary' && DefaultPdf" class="jh-handle flex-between">
                <div class="handle-item flex-center">
                    <div v-for="(item, index) in jhPdfList" :key="item.fileName"
                        :class="[ 's-14','jh-btn',active===index ? 'jh-btn-a': 'jh-btn-da']" @click="changePdf(index)">
                        {{item.fileTypeName}}</div>
                </div>
                <div style="background-color:#fff;" class=" flex-center pointer" @click="downLoadDesign">
                    <img class="icon-test" src="../../assets/img/home/test-download.png" alt="">
                    <div class="s-16 icon-de  pointer">下载</div>
                </div>
            </div>
            <div v-if="eduLevel==='primary' && Default">
                <div v-for="page in pageCount" :key="page" style="position: relative;background-color: #fff;">
                    <canvas :id="'canvas-pdf'+page"></canvas>
                    <div class="page-tips s-14 flex-center">第{{ page }}页/共{{ pageCount }}页</div>
                </div>
            </div>
            <div v-if="eduLevel==='primary' && !Default">
                <div class="preview" style="overscroll-behavior:contain;">
                    <iframe
                        :src="syncFileUrl"
                        id="iframeView"
                        width="100%"
                        height="100%"
                        scrolling="no"
                        frameborder="0"
                    >
                    </iframe>
                </div>
                <!-- <div v-for="page in pageCount" :key="page" style="position: relative;background-color: #fff;">
                    <canvas :id="'canvas-pdf'+page"></canvas>
                    <div class="page-tips s-14 flex-center">第{{ page }}页/共{{ pageCount }}页</div>
                </div> -->
            </div>
            <div v-if="eduLevel !=='primary'" id="jh-canvas-container">
                    <div id="canvasOne">
                        <div v-for="page in jhpageCountOne" :key="page+'one'" style="position: relative;background-color: #fff;">
                            <canvas :id="'canvas-pdf'+page"></canvas>
                            <div class="page-tips s-14 flex-center">第{{ page }}页/共{{ jhpageCountOne }}页</div>
                        </div>
                    </div>
                    <div v-if="contorlOnce" id="canvasTwo">
                        <div v-for="page in jhpageCountTwo" :key="page+'two'" style="position: relative;background-color: #fff;">
                            <canvas :id="'canvas-pdf'+page"></canvas>
                            <div class="page-tips s-14 flex-center">第{{ page }}页/共{{ jhpageCountTwo }}页</div>
                        </div>
                    </div>
            </div>
        </div>
        <div class="notSrc align-start" v-if="!DefaultPdf && online">
            <img class="res-empty" src="../../assets/img/cloud/empty.png" alt="">
            <div class="s-16">{{oldBookId.includes(bookId)?'旧版教材暂不提供教学设计，敬请谅解':'资源正在加紧制作，请耐心等待'}}</div>
        </div>
        <div class="notSrc align-start" v-if="!online">
            <img class="res-empty" src="../../assets/img/home/error-line.png" alt="">
            <div class="s-16">网络异常，请检查您的网络连接!</div>
        </div>
        <div class="test-download flex-center pointer" @click="downLoadDesign" v-if="eduLevel==='primary' && DefaultPdf">
            <img class="icon-test" src="../../assets/img/home/test-download.png" alt="">
            <div class="s-16 icon-de  pointer">下载</div>
        </div>
    </div>
</template>

<script>
// import $ from 'jquery'
import resource from '@/content/api/resource'
import PDFJS from '../../../../../static/utils/pdf/pdf'
import { Ini } from "../../utils/ini";
import { SqlLib } from '../../../../../static/lib/sqlite/SqlLib';
import { SqlLibUser } from '../../../../../static/lib/sqlite/service/SqlLibUser';

PDFJS.GlobalWorkerOptions.workerSrc = process.env.NODE_ENV === 'production' ? '../../../../app.asar/dist/electron/static/utils/pdf/pdf.worker.js' : '../../../../static/utils/pdf/pdf.worker.js'
export default {
    data () {
        let enviroment = Ini.readIni("data", "env")
        return {
            pdf_pages: [],
            pdfDoc: null,
            pageCount: 0, // pdf文件总页数
            pdfScale: 2,
            syncList:[],
            online: '',
            lessonName: '',
            lessonId: '',
            oldBookId: enviroment === "development_client" ? this.$CONST.global.devOldBookIds : this.$CONST.global.productOldBookIds,
            bookId: '',
            jhPdfList: [],
            eduLevel: window.eduLevel,
            eduLevelId: '',
            active: 0,
            jhCanvasTwoHidden: false,
            jhpageCountOne: 0,
            jhpageCountTwo: 0,
            fragmentOne: null,
            fragmentTwo: null,
            contorlOnce: false,
            Default:true,
            syncFileUrl:'',
            DefaultPdf:'',
            syncActive:-1,
            format:'',
            systemFile:false,
        }
    },
    created () {
    },
    computed: {
        canvasNum () {
            return jhPdfList.length === 0 ? 1 : jhPdfList.length
        }
    },
    mounted () {
        this.online = (localStorage.isOffline && localStorage.isOffline === 'false')
        let sqlLib = SqlLib.getInstance(window.$DBDIR)
        let user = SqlLibUser.queryCurrentUser(sqlLib)
        this.eduLevelId = user.eduLevelId
    },
    methods: {
        openDefault(){
            if (this.Default) {
                return
            }
            this.format = ''
            this.Default = true
            this.syncActive = -1
            this.loadPDF(this.DefaultPdf)
        },
        changeSyncFile(row,i){
            this.syncActive = i
            this.Default = false
            console.log(this.syncList);
            // this.loadPDF(row.previewUrl)
            this.syncFileUrl = row.previewUrl //用于展示
            this.downLoadUrl = row.url //用于下载
            this.format = row.format.replace(/\.?/g, '')
            console.log(this.format);
        },
        getDesign (lessonId, lessonName, bookId) {
            this.DefaultPdf = ''
            this.lessonName = lessonName
            this.lessonId = lessonId
            this.bookId = bookId
            if (this.online) {
                this.eduLevel === 'primary' ?
                resource.getNewTeachPlanByLessonId({ lessonId }).then(res => {
                    if (res.returnValue.length === 0) return
                    this.DefaultPdf = res.returnValue.teachPlanVOS[0].url
                    this.resourceId = res.returnValue.teachPlanVOS[0].id
                    res.returnValue.teachPlanVOS.forEach(item => {
                        if (item.type === '2') {
                            this.syncList.push(item)
                        }
                        if (item.type === '1') {
                            this.DefaultPdf = item.url
                            this.resourceId = item.id
                        }
                    });
                    if (res.returnValue.systemFileNum !== 0) {
                        this.systemFile = true
                        this.format = ''
                        this.loadPDF(this.DefaultPdf)
                    }else{
                        this.systemFile = false
                    }
                    if (res.returnValue.systemFileNum == 0 && res.returnValue.syncFileNum !==0) {
                        this.syncFileUrl = res.returnValue.teachPlanVOS[0].previewUrl
                        this.Default = false
                        this.syncActive = 0
                        this.downLoadUrl = res.returnValue.teachPlanVOS[0].url
                        this.format = res.returnValue.teachPlanVOS[0].format.replace(/\.?/g, '')
                        console.log(this.format);
                    }
                }) :
                resource.getMultiDocByLessonId({ lessonId }).then(res => {
                    if (res.returnValue.length === 0) return
                    this.jhPdfList = res.returnValue[0].multiDocChildrenVOS.splice(0, 2)
                    if (this.jhPdfList.length !== 0) {
                        if (!this.jhPdfList[0].fileTypeName.includes('导学案')) {
                            this.jhPdfList = this.jhPdfList.reverse()
                        }
                    }
                    this.DefaultPdf = this.jhPdfList[0].url
                    this.loadPDF(this.DefaultPdf)
                })
            }
        },
        downLoadDesign () {
            if (!this.DefaultPdf) return
            let apiParams = {
                resourceType: this.Default ? 'TeachPlan' : 'TeachPlan2',
                lessonId: this.lessonId,
                resourceId: this.resourceId,
                packageSize: this.pdfSize,
                eduLevelId: this.eduLevelId
            }
            var fileUrl = this.Default ? this.DefaultPdf : this.downLoadUrl
            apiParams.format = this.format
            console.log(apiParams.format);
            console.log(fileUrl);
            this.$showSaveDialog(fileUrl, '.design', this.lessonName + (this.eduLevel !== 'primary' ? ('-' + this.jhPdfList[this.active].fileTypeName) : '-教案'), apiParams)
        },
        changePdf (index) {
            this.$refs.test.scrollTop = 0
            if (index === 1 && !this.contorlOnce) {
                this.contorlOnce = true
            }
            this.active = index
            this.DefaultPdf = this.jhPdfList[index].url
            let dom = document.getElementById('jh-canvas-container')
            if (index === 1) {
                let targetDom = document.getElementById('canvasOne')
                if (!this.fragmentOne) {
                    this.fragmentOne = document.createDocumentFragment()
                    this.fragmentOne.appendChild(targetDom)
                }
                if (this.fragmentTwo) {
                    this.fragmentOne.appendChild(targetDom)
                    dom.appendChild(this.fragmentTwo)
                } else {
                    const src = this.jhPdfList[index].url
                    this.loadPDF(src)
                }
            }
            if (index === 0) {
                let targetDom = document.getElementById('canvasTwo')
                if (!this.fragmentTwo) {
                    this.fragmentTwo = document.createDocumentFragment()
                    this.fragmentTwo.appendChild(targetDom)
                }
                if (this.fragmentOne) {
                    this.fragmentTwo.appendChild(targetDom)
                    dom.appendChild(this.fragmentOne)
                }
            }

        },
        renderPDF (pdf, i, id) {
            pdf.getPage(i).then(page => {
                let canvas = document.getElementById(id);
                let ctx = canvas.getContext('2d');
                let dpr = window.devicePixelRatio || 1
                let bsr = ctx.webkitBackingStorePixelRatio ||
                    ctx.mozBackingStorePixelRatio ||
                    ctx.msBackingStorePixelRatio ||
                    ctx.oBackingStorePixelRatio ||
                    ctx.backingStorePixelRatio || 1
                let ratio = dpr / bsr
                let viewport = page.getViewport({ scale: this.pdfScale })
                canvas.width = viewport.width * ratio
                canvas.height = viewport.height * ratio
                canvas.style.width = 59.028 + 'vw'
                // that.pdf_div_width = viewport.width + 'px'

                // canvas.style.height = '100%'

                ctx.setTransform(ratio, 0, 0, ratio, 0, 0)

                // 将 PDF 页面渲染到 canvas 上下文中
                let renderContext = {
                    canvasContext: ctx,
                    viewport: viewport
                };
                page.render(renderContext);
            })
        },
        //读取pdf文件，并加载到页面中
        loadPDF (fileURL) {
            let mask = this.$downloadmask("#coursewareContainer", {
                title: '资源加载中',
                time: 15000,
                progress: false,
            });
            let pdf = PDFJS.getDocument({ url: fileURL, rangeChunkSize: 65536 * 5 })
            pdf.promise.then(val => {
                mask.close()
                if (this.eduLevel === 'primary') {
                    this.pageCount = val.numPages
                } else {
                    switch (this.active) {
                        case 0:
                            this.jhpageCountOne = val.numPages
                            break
                        case 1:
                            this.jhpageCountTwo = val.numPages
                            break
                        default:
                            console.log('pdf error')
                    }
                }
                val.getData().then(res => this.pdfSize = res.byteLength)
                for (let i = 1;i <= val.numPages;i++) {
                    let id = 'canvas-pdf' + i
                    try {
                        this.renderPDF(val, i, id)
                    } catch (error) {
                        console.log(error)
                    }
                }
            })
        }


    }
}
</script>

<style lang="scss">
.design {
    width: 100%;
    height: calc(100vh - 154px);
    background: rgba(205, 216, 225, 0.3);
    border-radius: 0.556vw;
    padding-top: 20px;
    margin-top: 20px;
    overflow: hidden;
    position: relative;
    .pdfBtn{
        justify-content:flex-start !important;
        width: 100%;
        border-bottom: 1px solid #dbdfe2;
        position: absolute;
        top: 16px;
        .syncPdf{
            margin-left: 10px;
        }
        margin-bottom: 20px;
        display: flex;
        button{
            width: 94px;
            height: 40px;
            background: #FAFAFA;
            border-radius: 6px 6px 0px 0px;
            border: 1px solid #D9D9D9;
            border-bottom: none !important;
            color:#D9D9D9 ;
        }
        .activeBtn{
            width: 94px;
            height: 40px;
            background: #FFFFFF;
            border-radius: 6px 6px 0px 0px;
            border: 1px solid #D9D9D9;
            color:#0185FE;
        }
    }
    .preview {
        border-radius: 3px;
        width: 100%;
        // overflow-y: hidden;
        #iframeView{
            height: calc(100vh - 154px);
            overflow-y: hidden; 
        }
        #ctn{
                div :last-child{
                    background-color: red;
                    height: auto!important;
                }
            }
    }
    .page-tips {
        position: absolute;
        bottom: 25px;
        background-color: #fff;
        color: #000;
        width: 100%;
    }
    .notSrc {
        transform: translateY(-60px);
        .res-empty {
            width: 360px;
            height: 360px;
        }
    }

    .test::-webkit-scrollbar {
        display: none;
    }
    .test {
        width: 59.028vw;
        height: calc(100% - 30px);
        border-radius: 8px 8px 0 0;
        overflow: auto;
        position: relative;
        transform: translateY(40px);
        .jh-handle {
            position: sticky;
            z-index: 99;
            top: 0;
            background: rgb(234, 241, 246);
            .icon-test {
                width: 24px;
                height: 24px;
                margin-right: 7px;
                vertical-align: middle;
            }
            .icon-de {
                height: 1.667vw;
                line-height: 1.667vw;
                margin-top: -2px;
            }
        }
        .handle-item {
            margin-bottom: 10px;
        }
        .jh-btn {
            width: 8.33vw;
            height: 40px;
            line-height: 40px;
            text-align: center;
            background: rgba(72, 148, 255, 1);
            border-radius: 8px;
            &:last-child {
                margin-left: 10px;
            }
        }
        .jh-btn-da {
            background-color: #fff;
            color: #606266;
        }
        .jh-btn-a {
            background-color: #4894ff;
            color: #fff;
        }
    }
    .test-download {
        position: fixed;
        right: 60px;
        top: 165px;
        .icon-test {
            width: 24px;
            height: 24px;
            margin-right: 7px;
            vertical-align: middle;
        }
        .icon-de {
            height: 1.667vw;
            line-height: 1.667vw;
            margin-top: -2px;
        }
    }
}
</style>
